package mushystuff.dtb.core.model;

import java.util.SortedSet;
import java.util.TreeSet;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.OneToMany;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.Sort;
import org.hibernate.annotations.SortType;
import org.hibernate.annotations.Where;

@Entity
public class Product extends PersistableBean {

    private String name;
    
    private boolean active;

    private SortedSet<UserStory> backlog = new TreeSet<UserStory>();

    private SortedSet<Sprint> sprints = new TreeSet<Sprint>();

    public Product() {
        super();
        active = true;
    }

    @Column(unique = true, nullable = false)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }

    @OneToMany(cascade=CascadeType.ALL)
    @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
    @Sort(type = SortType.NATURAL)
    @Where(clause="assignedSprint_id is null")
    public SortedSet<UserStory> getBacklog() {
        return backlog;
    }

    public void setBacklog(SortedSet<UserStory> backlog) {
        this.backlog = backlog;
    }

    @OneToMany(cascade=CascadeType.ALL)
    @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
    @Sort(type = SortType.NATURAL)
    public SortedSet<Sprint> getSprints() {
        return sprints;
    }

    public void setSprints(SortedSet<Sprint> sprints) {
        this.sprints = sprints;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj == this) {
            return true;
        }
        if (obj.getClass() != getClass()) {
            return false;
        }
        Product rhs = (Product) obj;
        return new EqualsBuilder().append(name, rhs.name).isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(61, 7).append(name).toHashCode();
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this).append("name", name).append(
                "backlog.size", backlog.size()).append("sprints.size",
                sprints.size()).toString();
    }

}
